package Client ;

import java.io.*;
import java.math.BigInteger;
import java.net.*;

import Paillier.Paillier;

public class VotingClient
{
	String FromServer = null;
	String ToServer = null;
	Socket clientSocket = null;
	BufferedReader inFromServer;
	PrintWriter outToServer;
	Paillier p;
	public VotingClient()
	{
		p = new Paillier();
		p.getKeys();
		inFromServer = null;
		try {
			clientSocket = new Socket("localhost", 6666);
		}
		catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
     
		outToServer = null;
		try {
			outToServer = new PrintWriter(clientSocket.getOutputStream(),true);
			inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String sendMessage(String query) throws IOException
	{
		outToServer.println("keys#"+p.n+"#"+p.g);
		outToServer.flush();
		String incomingKeys = inFromServer.readLine();
		System.out.println("INCKeys " +incomingKeys);
		String [] incomingKeysSp = incomingKeys.split("#");
		BigInteger n = new BigInteger(incomingKeysSp[1]);
		BigInteger g = new BigInteger(incomingKeysSp[2]);
		outToServer.println(p.EncryptByNG(query, n, g));
		outToServer.flush();
		String incoming = inFromServer.readLine();
		System.out.println("INC " +incoming);
		if(!incoming.equals(""))
		{
			String incomingD = p.Decrypt(incoming);
			System.out.println("INCD " + incomingD);
			outToServer.close();
		    clientSocket.close();
			return incomingD;
		}
		else
		{
			outToServer.close();
		    clientSocket.close();
			return incoming;
		}
		
		
	}
}
